import Vue from 'vue'
import qs from 'qs';
import axios from 'axios'
import router from '@/router'
import {Message} from 'element-ui';

Vue.use(router);

const Axios = axios.create({
    baseURL: process.env.VUE_APP_API_HOST,
    // baseURL: 'http://192.168.0.109/',
    timeout: 120000,
    responseType: "json",
    // withCredentials: true, // 跨域是否允许带cookie这些
    headers: {
        "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
    }
});
// 在请求或响应被 then 或 catch 处理前拦截它们
Axios.interceptors.request.use((config) => {
    const token = localStorage.getItem('token');
    if (token) {
        config.headers.Authorization = 'Bearer ' + token;
    } else { // 登录过验证token
        loginRedirect();
    }
    if (config.method === "post" || config.method === "put") {
        // 序列化
        config.data = qs.stringify(config.data);
    }
    return config;
}, err => {
    Message({
        showClose: true,
        message: '数据请求失败',
        type: 'error'
    });
    return Promise.reject(err);
});
// 请求后拦截器
Axios.interceptors.response.use(
    result => {
        //对响应数据做些事,根据定义的响应格式和状态码做处理
        if (result.status === 200) {
            return Promise.resolve(result.data);
        } else {
            return Promise.reject(result);
        }
    },
    error => {
        //常见错误操作
        if (!error.response) {
            if (error.message.includes('timeout')) {
                Message({
                    showClose: true,
                    message: '请求超时,请重试',
                    type: 'error'
                });
            } else {
                Message({
                    showClose: true,
                    message: error.message || '请求错误,请重试',
                    type: 'error'
                });
            }
            return;
        }
        let errCode = error.response.status;
        console.info('errCode', errCode);
        switch (errCode) {
            case 401:
                error.response.data.msg = "请登录后使用";
                router.push({path: '/login'});
                break;
        }
        // 返回 response 里的错误
        return Promise.reject(error.response);
    });

function loginRedirect() { // 跳转
    router.replace({name: 'login'});
}

export default {
    install: function (Vue, Option) {
        Object.defineProperty(Vue.prototype, "$http", {value: Axios});
    }
};